<?php
if (!defined('BASEPATH')) {
	exit('No direct script access allowed');
}

class Transaksi_penjualan extends CI_Controller {

	function __construct() {
		parent::__construct();
    //Memanggil Library
		$this->load->library('breadcrumb');
    $this->load->library('cart');
    //Memanggil Model
		$this->load->model('m_transaksi_penjualan');
		// Memanggil helper
		$this->load->helper('formatrp');
		$this->load->helper('id_date');
	}

	function index() {
		if (!$this->ion_auth->logged_in()) {
			redirect('login', 'refresh');
		} else {			
			// judul halaman
			$judul 					= 'Transaksi Penjualan';
			$data['judul'] 	= $judul;

			// Title HTML
			$this->layout->set_title($judul);
			
			// breadcrumb/untuk navigasi
      $this->breadcrumb->clear();
      $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
      $this->breadcrumb->add_crumb('Transaksi', site_url('transaksi_penjualan#'));
      $this->breadcrumb->add_crumb('Penjualan', site_url('transaksi_penjualan'));

      //Memanggil JS
      $this->layout->set_include('js', 'themes/general/bundle/select2/select2.min.js', 'header');
      $this->layout->set_include('css', 'themes/general/bundle/select2/select2.min.css');

      //Memanggil data obat
      $data['obat'] = $this->m_transaksi_penjualan->get_obat();

			$this->layout->theme('apotek','transaksi_penjualan/index', $data);
		}
	}

	function laporan() {
		//rule type pada function ini: Read
		$this->rule->type('R');

		//paging dan ambil data dari model
		$this->load->library('paging');                         		
		//Load library "paging"
		$config['sql']      				= $this->m_transaksi_penjualan->get();
    //Query SQL - bukan array lho ya, liat model
		$config['per_page'] 				= 5;                            
    //jumlah item tiap halaman
		$data = $this->paging->create_pagination($config);   				
    //Load fungsi di library "paging" untuk membuat pagination. 

    //Load helper "detail_obat"
    $this->load->helper('detail_obat');

		//menghilangkan session jika ada
		$this->session->unset_userdata('tgl_awal');
		$this->session->unset_userdata('tgl_akhir');

		// Memanggil JS
		$this->layout->set_include('js', 'themes/apotek/js/jquery-ui.js', 'header');
		$this->layout->set_include('js', 'themes/apotek/js/datepicker-id.js', 'header');
		//Memanggil CSS
		$this->layout->set_include('css', 'themes/apotek/css/olide-datepicker.css');
		$this->layout->set_include('css', 'themes/apotek/css/olide-custom.css');
    //Total Penjualan
    $data['total']  = $this->m_transaksi_penjualan->get_total();
		//judul halaman
		$judul          = 'Laporan Penjualan';
		$data['judul']  = $judul;
		
    // Title HTML
		$this->layout->set_title($judul);

    //breadcrumb/untuk navigasi
		$this->breadcrumb->clear();
		$this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
		$this->breadcrumb->add_crumb('Transaksi Penjualan', site_url('transaksi_penjualan#'));
		$this->breadcrumb->add_crumb($judul);

    //ambil data petugas
    $data['petugas']  = $this->m_transaksi_penjualan->get_petugas();
    //ambil data kelompok
    $data['kelompok'] = $this->m_transaksi_penjualan->get_kelompok();
    //ambil data obat
    $data['obat']     = $this->m_transaksi_penjualan->get_obat();

		//menggunakan theme back
		$this->layout->theme('apotek','transaksi_penjualan/laporan', $data);
	}

	function cari() {

		//rule type pada function ini: Read
		$this->rule->type('R');

    //Load helper "detail_obat"
    $this->load->helper('detail_obat');

		//buat cari
		if(isset($_POST)){
			$data['tgl_awal'] 	= $this->input->post('tgl_awal');
			$data['tgl_akhir'] 	= $this->input->post('tgl_akhir');
      $data['petugas']    = $this->input->post('petugas');
      $data['kelompok']   = $this->input->post('kelompok');
      $data['obat']       = $this->input->post('obat');
			$this->session->set_userdata('tgl_awal', $data['tgl_awal']);
			$this->session->set_userdata('tgl_akhir', $data['tgl_akhir']);
      $this->session->set_userdata('petugas', $data['petugas']);
      $this->session->set_userdata('kelompok', $data['kelompok']);
      $this->session->set_userdata('obat', $data['obat']);
		} else {
			$data['tgl_awal'] 	= $this->session->userdata('tgl_awal');
			$data['tgl_akhir'] 	= $this->session->userdata('tgl_akhir');
      $data['petugas']    = $this->session->userdata('petugas');
      $data['kelompok']   = $this->session->userdata('kelompok');
      $data['obat']       = $this->session->userdata('obat');
		}	

    //Mengambil data pencarian
    $tgl_awal 	= $data['tgl_awal'];
    $tgl_akhir 	= $data['tgl_akhir'];
    $petugas    = $data['petugas'];
    $kelompok   = $data['kelompok'];
    $obat       = $data['obat'];

    if($tgl_awal != '' && $tgl_akhir != ''){
  		//paging dan ambil data dari model
  		$this->load->library('paging');                         		//Load the "paging" library
      $config['sql']      				= $this->m_transaksi_penjualan->get_cari(iddate2dbdate($tgl_awal),iddate2dbdate($tgl_akhir),$petugas,$kelompok,$obat);//your SQL - bukan array lho ya...
      $config['per_page'] 				= 15;                            //Display items per page
      $data = $this->paging->create_pagination($config);   				//Load function in "paging" libraryfor create pagination. 
      //Total Penjualan
      $data['total']  = $this->m_transaksi_penjualan->get_cari_total(iddate2dbdate($tgl_awal),iddate2dbdate($tgl_akhir),$petugas,$kelompok,$obat);
    }else if($petugas != '' || $kelompok != '' || $obat != ''){
      //paging dan ambil data dari model
      $this->load->library('paging');                             //Load the "paging" library
      $config['sql']              = $this->m_transaksi_penjualan->get_cari_non_tgl($petugas,$kelompok,$obat);//your SQL - bukan array lho ya...
      $config['per_page']         = 15;                            //Display items per page
      $data = $this->paging->create_pagination($config);          //Load function in "paging" libraryfor create pagination. 
      //Total Penjualan
      $data['total']  = $this->m_transaksi_penjualan->get_cari_non_tgl_total($petugas,$kelompok,$obat);
    }else{
      //paging dan ambil data dari model
      $this->load->library('paging');                             //Load the "paging" library
      $config['sql']              = $this->m_transaksi_penjualan->get(); //your SQL - bukan array lho ya...
      $config['per_page']         = 15;                            //Display items per page
      $data = $this->paging->create_pagination($config);          //Load function in "paging" libraryfor create pagination. 
      //Total Penjualan
      $data['total']  = $this->m_transaksi_penjualan->get_total();
    }

    // Memanggil JS
		$this->layout->set_include('js', 'themes/apotek/js/jquery-ui.js', 'header');
		$this->layout->set_include('js', 'themes/apotek/js/datepicker-id.js', 'header');
		//Memanggil CSS
		$this->layout->set_include('css', 'themes/apotek/css/olide-datepicker.css');
		$this->layout->set_include('css', 'themes/apotek/css/olide-custom.css');

    //judul halaman
    $judul              = 'Pencarian Transaksi Penjualan';
    $data['judul']      = $judul;
    // Title HTML
    $this->layout->set_title($judul);
    //meta description jika perlu
    $this->layout->set_desc('Made with love by Raksa Abadi Informatika');
    //breadcrumb/untuk navigasi
    $this->breadcrumb->clear();
    $this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
    $this->breadcrumb->add_crumb('Laporan', site_url('transaksi_penjualan#'));
    $this->breadcrumb->add_crumb('Laporan Stok', site_url('transaksi_penjualan'));
    $this->breadcrumb->add_crumb($judul);

    //ambil data petugas
    $data['petugas']  = $this->m_transaksi_penjualan->get_petugas();
    //ambil data kelompok
    $data['kelompok'] = $this->m_transaksi_penjualan->get_kelompok();
    //ambil data obat
    $data['obat']     = $this->m_transaksi_penjualan->get_obat();

		//menggunakan theme back
    $this->layout->theme('apotek','transaksi_penjualan/laporan', $data);
  }

  public function detail($id){
		$this->rule->type('R');

		$judul = 'Detail Transaksi Penjualan';
		$data['judul'] = $judul;

		$this->layout->set_title($judul);
		$this->layout->set_desc('Made with love by Raksa Abadi Informatika');

		#breadcrumbs
		$this->breadcrumb->clear();
		$this->breadcrumb->add_crumb('Dasbor', site_url('dasbor'));
		$this->breadcrumb->add_crumb('Transaksi Penjualan', site_url('transaksi_penjualan'));
		$this->breadcrumb->add_crumb('Laporan', site_url('transaksi_penjualan/laporan'));
		$this->breadcrumb->add_crumb($judul);

		$data['data'] = $this->m_transaksi_penjualan->get_by_id($id);
		$data['detail_jual'] = $this->m_transaksi_penjualan->get_detail_by_id($id);
		$this->layout->theme('apotek','transaksi_penjualan/detail', $data);
	}

  function add_cart() {
    $obat = $this->m_transaksi_penjualan->get_obat_by($this->input->post('KdObat'));
   
    $insert = array(
      'id' => $this->input->post('KdObat'),
      'qty' => $this->input->post('Jumlah'),
      'price' => $obat['HargaJual'],
      'name' => $obat['NmObat']
    );
   
    $this->cart->insert($insert);
    $this->load->view('apotek/layouts/transaksi_penjualan/ajax_transaksi');
  }
  
  function delete_cart() {
    $rowid = $this->input->post('id');
    $this->cart->update(array(
     'rowid' => $rowid,
     'qty' => 0
    ));
    $this->load->view('apotek/layouts/transaksi_penjualan/ajax_transaksi');
  }

  function total() {
    $data['total'] = $this->cart->total();
    $this->load->view('apotek/layouts/transaksi_penjualan/ajax_total',$data);
  }

  function subtotal() {
    $data['total'] = $this->cart->total();
    $this->load->view('apotek/layouts/transaksi_penjualan/ajax_subtotal',$data);
  }

  function kembalian() {
    $total = $this->cart->total();
    $bayar = $this->input->post('bayar');
    $data['kembali'] = $bayar - $total;
    $this->load->view('apotek/layouts/transaksi_penjualan/ajax_kembalian',$data);
  }

  function simpan_transaksi() {
    $dataInsert = array(
      'Tanggal'     => date('Y-m-d'), 
      'Keterangan'  => $this->input->post('keterangan'),
      'id_user'     => user_id()
    );

    if(!$this->m_transaksi_penjualan->saveTransaksi($dataInsert)){
      $this->session->set_flashdata('gagal', 'Transaksi Gagal ditambahkan');
      redirect('transaksi_penjualan','refresh');
    }else{
      $id = $this->db->insert_id();
      $this->session->set_flashdata('sukses', 'Transaksi Sukses ditambahkan');
      foreach ($this->cart->contents() as $items) {
        $dataDetailInsert = array(
          'KdJual'  => $id,
          'KdObat'  => $items['id'], 
          'Jumlah'  => $items['qty'],
          'Harga'   => $items['price'],
        );
        $this->m_transaksi_penjualan->saveDetailTransaksi($dataDetailInsert);
      }
      $this->cart->destroy();
      redirect('transaksi_penjualan');
    }    
  }

  function excel(){
  	$this->rule->type('R');
    //Load helper "detail_obat"
    $this->load->helper('detail_obat');
		//load our new PHPExcel library
  	$this->load->library('excel');
		//activate worksheet number 1
  	$this->excel->setActiveSheetIndex(0);
		//name the worksheet
  	$this->excel->getActiveSheet()->setTitle('Laporan Penjualan');
		//set cell A1 content with some text
    $tgl_awal   = $this->session->userdata('tgl_awal');
    $tgl_akhir  = $this->session->userdata('tgl_akhir');
    $petugas    = $this->session->userdata('petugas');
    $kelompok   = $this->session->userdata('kelompok');
    $obat       = $this->session->userdata('obat');

    if($tgl_awal != '' && $tgl_akhir != ''){
      $this->excel->getActiveSheet()->setCellValue('A1', 'Laporan Penjualan Tanggal '.id_date($tgl_awal,'long').' s.d. '.id_date($tgl_akhir,'long').'');
    }else{
  	  $this->excel->getActiveSheet()->setCellValue('A1', 'Laporan Penjualan');
    }

    $this->excel->setActiveSheetIndex(0)->mergeCells('A2:A3');
  	$this->excel->getActiveSheet()->setCellValue('A2', 'No.');
  	$this->excel->setActiveSheetIndex(0)->mergeCells('B2:B3');
  	$this->excel->getActiveSheet()->setCellValue('B2', 'Kode Transaksi');
  	$this->excel->setActiveSheetIndex(0)->mergeCells('C2:C3');
  	$this->excel->getActiveSheet()->setCellValue('C2', 'Tanggal');
  	$this->excel->setActiveSheetIndex(0)->mergeCells('D2:D3');
  	$this->excel->getActiveSheet()->setCellValue('D2', 'Petugas');
  	$this->excel->setActiveSheetIndex(0)->mergeCells('E2:E3');
  	$this->excel->getActiveSheet()->setCellValue('E2', 'Keterangan');
  	$this->excel->setActiveSheetIndex(0)->mergeCells('F2:J2');
  	$this->excel->getActiveSheet()->setCellValue('F2', 'Detail Penjualan');
  	$this->excel->getActiveSheet()->setCellValue('F3', 'Kode Obat');
  	$this->excel->getActiveSheet()->setCellValue('G3', 'Nama Obat');
  	$this->excel->getActiveSheet()->setCellValue('H3', 'Jumlah');
  	$this->excel->getActiveSheet()->setCellValue('I3', 'Harga');
  	$this->excel->getActiveSheet()->setCellValue('J3', 'Total');

		//change the font size
  	$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);
		//make the font become bold
  	$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
		//merge cell A1 until D1
  	$this->excel->getActiveSheet()->mergeCells('A1:J1');
		//set aligment to center for that merged cell (A1 to D1)
  	$this->excel->getActiveSheet()->getStyle('A1:J3')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		//set style
  	$TitleStyle = array(
  		'borders' => array(
  			'allborders' => array(
  				'style' => PHPExcel_Style_Border::BORDER_THIN
  				)
  			),
  		'fill' => array(
  			'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => '00994C') // hijau tua
            ),
  		'font'  => array(
  			'bold'  => false,
  			'color' => array('rgb' => 'FFFFFF'),
  			'size'  => 15,
  			'name'  => 'Verdana'
  			)
  		);

  	$HeaderStyle = array(
  		'borders' => array(
  			'allborders' => array(
  				'style' => PHPExcel_Style_Border::BORDER_THIN
  				)
  			),
  		'fill' => array(
  			'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => '32CD32') // hijau
            ),
  		'font'  => array(
  			'bold'  => true
  			)
  		);

  	$ContentStyle = array(
  		'borders' => array(
  			'allborders' => array(
  				'style' => PHPExcel_Style_Border::BORDER_THIN
  				)
  			),
  		'fill' => array(
  			'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'FFFF00') // kuning
            ),
      'aligment' =>array(
            'vertical'=> PHPExcel_Style_Alignment::VERTICAL_CENTER='center'
        )
  		);

  	$this->excel->getActiveSheet()->getStyle('A1:J1')->applyFromArray($TitleStyle);
  	$this->excel->getActiveSheet()->getStyle('A2:J3')->applyFromArray($HeaderStyle);

    if($tgl_awal != '' && $tgl_akhir != ''){
      $list_data = $this->m_transaksi_penjualan->get_export(iddate2dbdate($tgl_awal),iddate2dbdate($tgl_akhir),$petugas,$kelompok,$obat);
    }else if($petugas != '' || $kelompok != '' || $obat != ''){
      $list_data = $this->m_transaksi_penjualan->get_export_non_tgl($petugas,$kelompok,$obat);
    }else{
      $list_data = $this->m_transaksi_penjualan->get_export_all();
    }

    $grand_total = 0;
  	$cols = 4;
  	$num = 1;
  	foreach($list_data as $row){
      if($kelompok != '' || $obat != ''){
        $detail   = get_detail_jual_by($row['KdJual'],$kelompok,$obat);
      }else{
        $detail   = get_detail_jual($row['KdJual']);
      }
  		$col = $cols;
  		$col_mulai = $col;

  		$this->excel->getActiveSheet()->setCellValue('A' . $col, $num++);
  		$this->excel->getActiveSheet()->setCellValue('B' . $col, $row['KdJual']);
  		$this->excel->getActiveSheet()->setCellValue('C' . $col, id_date($row['Tanggal'],'short'));
  		$this->excel->getActiveSheet()->setCellValue('D' . $col, $row['nickname']);
  		$this->excel->getActiveSheet()->setCellValue('E' . $col, $row['Keterangan']);

  		foreach ($detail as $data) {
  			$col = $cols++;
  			$total 	= $data['Jumlah'] * $data['Harga'];
	  		$this->excel->getActiveSheet()->setCellValue('F' . $col, $data['KdObat']);
	  		$this->excel->getActiveSheet()->setCellValue('G' . $col, $data['NmObat']);
	  		$this->excel->getActiveSheet()->setCellValue('H' . $col, $data['Jumlah']);
	  		$this->excel->getActiveSheet()->setCellValue('I' . $col, $data['Harga']);
	  		$this->excel->getActiveSheet()->setCellValue('J' . $col, $total);

	  		$this->excel->getActiveSheet()->getStyle('F' . $col)->applyFromArray($ContentStyle);
	  		$this->excel->getActiveSheet()->getStyle('G' . $col)->applyFromArray($ContentStyle);
	  		$this->excel->getActiveSheet()->getStyle('H' . $col)->applyFromArray($ContentStyle);
	  		$this->excel->getActiveSheet()->getStyle('I' . $col)->applyFromArray($ContentStyle);
	  		$this->excel->getActiveSheet()->getStyle('J' . $col)->applyFromArray($ContentStyle);
	  		$grand_total = $grand_total + $total;
	  	}

	  	$this->excel->setActiveSheetIndex(0)->mergeCells('A'.$col_mulai.':A'.$col.'');
  		$this->excel->setActiveSheetIndex(0)->mergeCells('B'.$col_mulai.':B'.$col.'');
  		$this->excel->setActiveSheetIndex(0)->mergeCells('C'.$col_mulai.':C'.$col.'');
  		$this->excel->setActiveSheetIndex(0)->mergeCells('D'.$col_mulai.':D'.$col.'');
  		$this->excel->setActiveSheetIndex(0)->mergeCells('E'.$col_mulai.':E'.$col.'');

  		$this->excel->getActiveSheet()->getStyle('A'.$col_mulai.':A'.$col.'')->applyFromArray($ContentStyle);
  		$this->excel->getActiveSheet()->getStyle('B'.$col_mulai.':B'.$col.'')->applyFromArray($ContentStyle);
  		$this->excel->getActiveSheet()->getStyle('C'.$col_mulai.':C'.$col.'')->applyFromArray($ContentStyle);
  		$this->excel->getActiveSheet()->getStyle('D'.$col_mulai.':D'.$col.'')->applyFromArray($ContentStyle);
  		$this->excel->getActiveSheet()->getStyle('E'.$col_mulai.':E'.$col.'')->applyFromArray($ContentStyle);
  	}

  	$col = $cols++;
  	$this->excel->getActiveSheet()->setCellValue('A'.$col, 'Total Penjualan');
  	$this->excel->setActiveSheetIndex(0)->mergeCells('A'.$col.':I'.$col.'');
  	$this->excel->getActiveSheet()->getStyle('A'.$col.':J'.$col)->applyFromArray($HeaderStyle);
  	$this->excel->getActiveSheet()->setCellValue('J'.$col, $grand_total);


  	$this->excel->getActiveSheet()->getColumnDimension("A")->setAutoSize(true);
  	$this->excel->getActiveSheet()->getColumnDimension("B")->setAutoSize(true);
  	$this->excel->getActiveSheet()->getColumnDimension("C")->setAutoSize(true);
  	$this->excel->getActiveSheet()->getColumnDimension("D")->setAutoSize(true);
  	$this->excel->getActiveSheet()->getColumnDimension("E")->setAutoSize(true);
  	$this->excel->getActiveSheet()->getColumnDimension("F")->setAutoSize(true);
  	$this->excel->getActiveSheet()->getColumnDimension("G")->setAutoSize(true);
  	$this->excel->getActiveSheet()->getColumnDimension("H")->setAutoSize(true);
  	$this->excel->getActiveSheet()->getColumnDimension("I")->setAutoSize(true);
  	$this->excel->getActiveSheet()->getColumnDimension("J")->setAutoSize(true);

		$filename='laporan penjualan.xls'; //save our workbook as this file name
		header('Content-Type: application/vnd.ms-excel'); //mime type
		header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
		header('Cache-Control: max-age=0'); //no cache

		//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
		//if you want to save it as .XLSX Excel 2007 format
		$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');  
		//force user to download the Excel file without writing it to server's HD
		$objWriter->save('php://output');
	}

}
